package com.liweitong.minhang.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liweitong.minhang.entity.Flight;
import com.liweitong.minhang.entity.NoteInfo;
import com.liweitong.minhang.entity.Punch;
import com.liweitong.minhang.service.NoteInfoService;
import com.liweitong.minhang.service.PunchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.sql.Wrapper;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author Weton Li
 * @Date 2023/2/28 00:04
 */
@Controller
public class PunchController {
    @Autowired
    PunchService punchService;


    //    @ResponseBody
    @GetMapping("/getPunchInfo")
    public String getPunchInfo(Model model) {
        List<Punch> list = punchService.list();
//        model.addAttribute("flights", list);
        model.addAttribute("punches", list);
//        return "createNote";
        return "list";
    }

    @GetMapping("/toCreateNoteHtml")
    public String toCreateNoteHtml(Model model) {
        return "createNote";
    }


//    @PostMapping("/login.html")
//    public String login() {
//        return "redirect:/list.html";
//    }

    //    点击人脸识别后，转发到list.html打卡页面
    @RequestMapping("/")
    public String toListPage() {
        return "forward:/getNoteInfo";
    }

    /**
     * 点击刷新去flushPunch.html
     *
     * @param model
     * @return
     */
    @RequestMapping("/flushPageToFlushPunch")
    public String flushPageToFlushPunch(Model model) {
        List<Punch> list = punchService.list();
//        model.addAttribute("flights", list);
        // cal CurrentDayMoneyAndTotalMoney,and to set.


        model.addAttribute("punches", list);
        return "flushPunch";
    }

    // 暂时用不上
    // 本来都是去flushPageToFlushPunch，现在被calCurrAndTotalMoney继承
    @RequestMapping("/calCurrAndTotalMoney")
    public String myCal() {
        QueryWrapper<Punch> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("pid").last("limit 1");
        Punch punch = punchService.getOne(wrapper);
        System.out.println(punch);
        int baseAwardRMB = 0, basePunishRMB = 0, extraAward = 0, extraPunish = 0;
        if (punch.getBaseAwardRMB() != null) {
            baseAwardRMB = Integer.parseInt(punch.getBaseAwardRMB());
            System.out.println(baseAwardRMB);
        }
        if (!punch.getBasePunishRMB().equals("待评价")) {
            basePunishRMB = Integer.parseInt(punch.getBasePunishRMB());
            System.out.println(basePunishRMB);

        }
        if (!punch.getExtraAward().equals("待评价")) {
            extraAward = Integer.parseInt(punch.getExtraAward());
        }
        if (!punch.getExtraPunish().equals("待评价")) {
            extraPunish = Integer.parseInt(punch.getExtraPunish());
        }

        int oneAward = baseAwardRMB + basePunishRMB + extraAward + extraPunish;
        int doubleAward = (baseAwardRMB + basePunishRMB + extraAward + extraPunish) * 2;
        int res = punch.getIsDoubleAward().equals("是") ? doubleAward : oneAward;
        punch.setCurrentDayMoney(String.valueOf(res));
        System.out.println(punch.getCurrentDayMoney());
        int i = 0;
        if (punch.getTotalMoney() != null) {
            i = Integer.parseInt(punch.getTotalMoney());
        }
        int i1 = i + res;

        punch.setTotalMoney(String.valueOf(i1));
        System.out.println(punch.getTotalMoney());
        punchService.updateById(punch);

        return "redirect:/flushPageToFlushPunch";
    }


    @RequestMapping("/queryWithConditionalByPunch")
    public String queryWithConditional(String finishStatus, String punchTime, Model model) {

//        QueryWrapper<Punch> wrapper = new QueryWrapper<>();
//        String fno = flightQueryVo.getFno();
//        Date fdate = flightQueryVo.getFdate();
//        if (!StringUtils.isEmpty(finishStatus)) {
//            wrapper.eq("finishStatus", finishStatus);
//        }
//        if (!StringUtils.isEmpty(punchTime)) {
//            wrapper.eq("punchTime", punchTime);
//        }
//        List<Punch> list = punchService.list(wrapper);
//        model.addAttribute("punches",list);
        return "list";
    }

    // todo保存打卡，也需要获取最后一条数据的 钱包余额？
    @RequestMapping("/savePunchCard")
    @ResponseBody
    public void savePunchCard(String id) {
        Punch punch = new Punch();

        int size = punchService.list().size();
        size++;
        punch.setPid(Integer.toString(size));

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String currTime = formatter.format(date); // 存入数据库的格式化字符串标准数据
        System.out.println(currTime);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd");
        Date curDate = new Date(System.currentTimeMillis());
        String currDay = simpleDateFormat.format(curDate);
        System.out.println(currDay);

        // 查数据库最后一条数据（最近一次打卡记录）的日期
        QueryWrapper<Punch> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("pid").last("limit 1");
        Punch punchOne = punchService.getOne(wrapper);
        String lastpunchTime = punchOne.getPunchTime();
        System.out.println("数据库中取出的最后一条数据" + lastpunchTime);
        String mm = lastpunchTime.substring(8, 10);
        if (currDay.equals(mm)) {
            // 不重复打卡，只更新updateTime
            punchOne.setPunchUpdateTime(currTime);
            punchService.updateById(punchOne);
        } else {
            punch.setPunchTime(currTime);
            punchService.save(punch);
        }
    }


    /**
     * 前往提现页面处理器
     *
     * @param model
     * @return
     */
    @RequestMapping("/toRMBtotalHtml")
    public String toRMBtotalHtml(Model model) {
        return "forward:/dispWalletRMB";
    }

    /**
     * 展示提现页面可提现余额
     * 邮箱
     * @param model
     * @return
     */
    @RequestMapping("/dispWalletRMB")
    public String dispWalletRMB(Model model) {
        QueryWrapper<Punch> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("pid").last("limit 1,1"); // 先降序，从第1+1行开始，检索一行数据
        Punch punchlastSecond = punchService.getOne(wrapper);
        String lastSecondTotalMoney = punchlastSecond.getTotalMoney();
        System.out.println("lastSecondTotalMoney:" + lastSecondTotalMoney);
        model.addAttribute("lastSecondTotalMoney", lastSecondTotalMoney);
        return "RMBtotal.html";
    }

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Autowired
    private JavaMailSender javaMailSender;
    @RequestMapping("/takeAway")
    @ResponseBody
    public void takeAway(@RequestParam("wantTakenRMB") String wantTakenRMB,@RequestParam("zfbNumber") String zfbNumber) {
        QueryWrapper<Punch> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("pid").last("limit 1,1"); // 先降序，从第1+1行开始，检索一行数据
        Punch punchlastSecond = punchService.getOne(wrapper);
        String lastSecondTotalMoney = punchlastSecond.getTotalMoney();
        int canTakenTotolMoney = Integer.parseInt(lastSecondTotalMoney);
        int sub = Integer.parseInt(wantTakenRMB);
        int res = canTakenTotolMoney;
        if (canTakenTotolMoney >= sub) {
            res = canTakenTotolMoney - sub;
        }
        punchlastSecond.setTotalMoney(String.valueOf(res));
        punchService.updateById(punchlastSecond);

        // 发邮件
        System.out.println(Thread.currentThread().getName());
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置发件人账号
        message.setFrom(fromEmail);
        // 设置收件人账号
        message.setTo("243903449@qq.com");
        // 设置邮件标题
        message.setSubject("园园提现申请");
        // 设置邮件内容
        String content = "提现金额："+wantTakenRMB+"元 And 支付宝："+zfbNumber;
        message.setText(content);
        javaMailSender.send(message);
    }

    /**
     * 充值
     */
//    @RequestMapping("/recharge")
//    @ResponseBody
//    public void recharge(String chongzhi){
//        QueryWrapper<Punch> wrapper = new QueryWrapper<>();
//        wrapper.orderByDesc("pid").last("limit 1,1"); // 先降序，从第1+1行开始，检索一行数据
//        Punch punchlastSecond = punchService.getOne(wrapper);
//        String lastSecondTotalMoney = punchlastSecond.getTotalMoney();
//        int lastSecond = Integer.parseInt(lastSecondTotalMoney);
//        int cz = Integer.parseInt(chongzhi);
//        int res = lastSecond+cz;
//    }

    /**
     * 前往单独自审核
     *
     * @param model
     * @return
     */
    @RequestMapping("/set")
    public String toShenhe(Model model) {
        List<Punch> list = punchService.list();
//        model.addAttribute("flights", list);
        // cal CurrentDayMoneyAndTotalMoney,and to set.


        model.addAttribute("punches", list);
        return "set";
    }

    /**
     * 只负责跳转到民航修改页面
     *
     * @param
     * @return
     */
    @RequestMapping("/toUpdatePunch/{pid}")
    public String toUpdatePunch(@PathVariable("pid") String pid, Model model) {
        Punch punch = punchService.getById(pid);
        model.addAttribute("flight", punch);
        return "update";
    }

    @RequestMapping("/updatePunchInfo")
    public String setSave(Punch punch){
        punchService.updateById(punch);
        return "redirect:/set";
    }

    @RequestMapping("/toZhuanpan")
    public String toZhuanpan(){
        return "choujiang";
    }
}
